package flyshoes.service.serviceImpl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import flyshoes.mybatis.entity.ShippingInformation;
import flyshoes.mybatis.entity.UserBaseInfo;
import flyshoes.mybatis.entity.UserDetailInfo;
import flyshoes.mybatis.mapper.UserdetailinfoMapper;
import flyshoes.mybatis.service.serviceImpl.ShippinginformationServiceImpl;
import flyshoes.mybatis.service.serviceImpl.UserbaseinfoServiceImpl;
import flyshoes.mybatis.service.serviceImpl.UserdetailinfoServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import flyshoes.mybatis.entity.Result;
import flyshoes.utils.JwtUtil;
import flyshoes.utils.Md5Util;
import flyshoes.utils.ThreadLocalUtil;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class UserServiceImpl {
    private final UserbaseinfoServiceImpl baseInfoService;
    private final UserdetailinfoServiceImpl detailInfoService;
    private final RedisTemplate redisTemplate;
    private final ShippinginformationServiceImpl addressService;
    private final UserdetailinfoMapper detailinfoMapper;

    @Transactional
    /**登录*/
    public Result login(Map users) {
        String phoneNumber = (String) users.get("phoneNumber");
        String password = (String) users.get("password");
        String code = (String) users.get("code");
        String captchaId = (String) users.get("captchaId");
        UserBaseInfo userDb = baseInfoService.lambdaQuery().eq(UserBaseInfo::getPhoneNumber, phoneNumber).one();
        String token = "";
        if (userDb == null) {
            return Result.fail(400, "此用户未注册");
        }

        String captchaKey = "captcha:" + captchaId;
        String rediscode = (String) redisTemplate.opsForValue().get(captchaKey);
        if (code.equals(rediscode)) {

        } else {
            return Result.fail(400, "验证码错误");
        }
        if (Md5Util.passwordIsTrue(password, userDb.getPassword())) {
            token = JwtUtil.genToken(userDb.getId());
            String tokenKey = "token:" + token;
            redisTemplate.opsForValue().set(tokenKey, token,168, TimeUnit.HOURS);
        } else {
            return Result.fail(400, "密码错误");
        }
        return Result.success(token);
    }

    @Transactional
    /**注册*/
    public Result<UserBaseInfo> register(UserBaseInfo users) {
        UserBaseInfo userDb = baseInfoService.lambdaQuery().eq(UserBaseInfo::getPhoneNumber, users.getPhoneNumber()).one();
        if (userDb == null) {
            String md5 = Md5Util.getMD5(users.getPassword());
            users.setPhoneNumber(users.getPhoneNumber());
            users.setPassword(md5);
            baseInfoService.save(users);
            UserDetailInfo detailInfo = new UserDetailInfo();
            detailInfo.setUserId(users.getId());
            detailInfoService.save(detailInfo);
            return Result.success(null);
        } else {
            return Result.fail(400, "注册失败，该手机号已存在");
        }
    }

    @Transactional
    /**更新密码*/
    public Result updatePassword(String newPassword) {
        Integer userId = ThreadLocalUtil.get();
        UserBaseInfo userDb = baseInfoService.lambdaQuery().eq(UserBaseInfo::getId, userId).one();
        userDb.setPassword(Md5Util.getMD5(newPassword));
        baseInfoService.updateById(userDb);
        return Result.success(null);
    }

    @Transactional
    /**检查旧密码是否正确*/
    public boolean checkOldPassword(String oldPassword) {
        //System.out.println("现在的数据类型是------------------------------------------"+ThreadLocalUtil.get().getClass().getSimpleName());
        //System.out.println("现在的userid是------------------------------------------"+ThreadLocalUtil.get());
        Integer userId = ThreadLocalUtil.get();
        UserBaseInfo userDb = baseInfoService.lambdaQuery().eq(UserBaseInfo::getId, userId).one();
        if (Md5Util.passwordIsTrue(oldPassword, userDb.getPassword())) {
            return true;
        } else {
            return false;
        }
    }

    @Transactional
    /**增加收货地址*/
    public Result newAddress(ShippingInformation address) {
        Integer userId = ThreadLocalUtil.get();
        ShippingInformation addressDb = addressService.lambdaQuery()
                .eq(ShippingInformation::getRecipientName, address.getRecipientName())
                .eq(ShippingInformation::getPhoneNumber, address.getPhoneNumber())
                .eq(ShippingInformation::getAddress, address.getAddress()).one();
        if (addressDb == null) {
            address.setUserId(userId);
            address.setCreatedTime(LocalDateTime.now());
            addressService.save(address);
            return Result.success("新增地址成功");
        } else {
            return Result.fail(400, "不得重复添加相同的收货人信息");
        }

    }
    @Transactional
    public Result deleteAddress(Integer addressId){
        return Result.success(addressService.removeById(addressId));
    }

    @Transactional
    /**更新收货地址*/
    public Result updateAddress(ShippingInformation shippingInformation) {
//        String oldRecipientName = address.get("oldRecipientName");
//        String oldPhoneNumber = address.get("oldPhoneNumber");
//        String oldAddress = address.get("oldAddress");
//        String newRecipientName = address.get("newRecipientName");
//        String newPhoneNumber = address.get("newPhoneNumber");
//        String newAddress = address.get("newAddress");
//        ShippingInformation addressDb = addressService.lambdaQuery()
//                .eq(ShippingInformation::getRecipientName, oldRecipientName)
//                .eq(ShippingInformation::getPhoneNumber, oldPhoneNumber)
//                .eq(ShippingInformation::getAddress, oldAddress)
//                .one();
//        if (StrUtil.isNotBlank(newRecipientName)) {
//            addressDb.setRecipientName(newRecipientName);
//        }else {
//            addressDb.setRecipientName(oldRecipientName);
//        }
//        if (StrUtil.isNotBlank(newPhoneNumber)) {
//            addressDb.setPhoneNumber(newPhoneNumber);
//        }else {
//            addressDb.setPhoneNumber(oldPhoneNumber);
//        }
//        if (StrUtil.isNotBlank(newAddress)) {
//            addressDb.setAddress(newAddress);
//        }else {
//            addressDb.setAddress(oldAddress);
//        }
        addressService.updateById(shippingInformation);
        return Result.success("更新地址成功");
    }

    @Transactional
    /**更新用户信息*/
    public Result updateMyInfo(UserDetailInfo myInfo) {
        Integer userId = ThreadLocalUtil.get();
        UpdateWrapper<UserDetailInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id",userId);
        detailinfoMapper.update(myInfo, updateWrapper);
        return Result.success("更新成功");
    }

    @Transactional
    /**查找用户信息*/
    public Result<UserDetailInfo> queryMyInfo() {
        Integer userId = ThreadLocalUtil.get();
        UserDetailInfo userDetailInfo = detailInfoService.lambdaQuery().eq(UserDetailInfo::getUserId, userId).one();
        return Result.success(userDetailInfo);
    }
    @Transactional
    //查找用户地址信息
    public Result myAddress(){
        Integer userId = ThreadLocalUtil.get();
        List<ShippingInformation> list = addressService.lambdaQuery().eq(ShippingInformation::getUserId, userId).list();
        return Result.success(list);
    }
}
